import utils from "./util";


const app = getApp();
console.log(app,'==app')

app.globalData.bleDisNetwork = {
  bleDeviceList: [],
  MAC: "",
  UUID: ""
}

class BleDisNetwork {
    constructor() {
        // 蓝牙设备id
        this.deviceId = null;
        // 蓝牙设备列表
        this.bleDeviceList = [];
        // 设备服务id
        this.serviceId = null;
        // 设备的某个特征值
        this.characteristicId = null;
        this.mtuTimer = null;
        this.mtuVal = 0
        this.platform = null;
        this.notifyPromise = null;
    }
    getSystemInfo() {
        let that = this;
        if (that.platform) {
            return Promise.resolve(that.platform)
        }
        return new Promise((reslove, reject) => {
            wx.getSystemInfo({
                success: function (res) {
                    console.log(res);
                    // res.platform 可能的值有 "android", "ios", "devtools", "windows"
                    const platform = res.platform.toLowerCase();
                    that.platform = platform;
                    reslove(platform);
                }
            })
        })

    }

    // 初始化蓝牙模块
    openBluetooth() {
        let that = this;
        // 版本过低兼容
        if (!wx.openBluetoothAdapter) {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
            })
            return;
        }
        return new Promise((reslove, reject) => {
            wx.openBluetoothAdapter({
                success: function (res) {
                    console.log("初始化蓝牙适配器成功" + JSON.stringify(res));
                    reslove(1)
                },
                fail(err) {
                    console.log("初始化蓝牙适配器失败" + JSON.stringify(err));
                    if (err.errMsg === 'openBluetoothAdapter:fail already opened') {
                        // 蓝牙适配器已经打开
                        console.log("蓝牙适配器已经打开");
                        reslove(1)
                        return
                    }
                    // 初始化蓝牙适配器失败
                    reject(0)
                    wx.showToast({
                        title: "蓝牙适配失败，请检查手机蓝牙和定位功能是否打开",
                        icon: "none",
                        duration: 2000,
                    });
                }
            });
        })
    }
    // 开启蓝牙设备搜索
    deviceSearch(searchVal, type = 'deviceId', fn = (device) => {}) {
        let that = this;
        console.log("打开蓝牙设备搜索");
        // 获取本机蓝牙适配器状态
        wx.getBluetoothAdapterState({
            success(res) {
                console.log("获取本机蓝牙适配器状态", res);
            },
        });
        // 监听蓝牙适配器状态变化事件
        wx.onBluetoothAdapterStateChange(function (res) {
            console.log("搜索状态：", res.discovering);
            console.log("蓝牙状态：", res.available);
        });
        // 开始搜寻附近的蓝牙外围设备
        wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: false, //是否允许重复上报同一设备
            success(res) {
                console.log("开始搜寻附近的蓝牙外围设备", res);
                // 20s后停止搜索
                setTimeout(() => that.stopSearchBluetooth(), 20000);
            },
        });
        // 监听搜索到新设备的事件
        wx.onBluetoothDeviceFound(function (devices) {

            let device = devices.devices[0];
            if (!device) return;

            console.info('设备11111111=====', device);
            console.info('searchValsearchVal=====', searchVal);
            console.info('设备=====', device.name);
            if (searchVal) {
                // 连接指定设备
                if (type === 'deviceId' && device.deviceId === searchVal) {
                    console.log('连接指定设备', device.deviceId);
                    that.deviceId = device.deviceId;
                    that.connectBluetooth(deviceId);
                    that.stopSearchBluetooth();
                } else if (type === 'name' && device.name.indexOf(searchVal) > -1) {
                    console.log('查询设备', device.name);
                    fn && fn(device)
                }
                return;
            } else {
                fn && fn(device)
            }
        });
        // 获取在蓝牙模块生效期间所有搜索到的蓝牙设备。包括已经和本机处于连接状态的设备
        wx.getBluetoothDevices({
            success(res) {
                console.log(
                    "获取在蓝牙模块生效期间所有搜索到的蓝牙设备。包括已经和本机处于连接状态的设备",
                    res
                );
            },
        });
    }
    // 关闭蓝牙设备搜索
    stopSearchBluetooth() {
        let that = this;
        wx.stopBluetoothDevicesDiscovery({
            success(res) {
                console.log("关闭蓝牙设备搜索", res);
                console.log(that.bleDeviceList, "bleDeviceList");
            },
        });
    }

    //获取蓝牙最大传输字节
    getBLEMTU() {
        let that = this;
        if (that.mtuVal) {
            return Promise.resolve(that.mtuVal)
        }
        return new Promise((reslove, reject) => {
            wx.getBLEMTU({
                deviceId: that.deviceId,// 目标蓝牙设备ID
                writeType: 'write',// 写入类型
                success(res) {
                    that.mtuVal = res.mtu
                    console.log('获取mtu成功', that.mtuVal)
                    reslove(that.mtuVal)
                },
                fail(err) {
                    console.error(err)
                    reslove(20)
                }
            })
        })

    }
    setAndroidMTU(deviceId) {
        let that = this;
        console.log('处理安卓协商低功耗最大传输单元失败的方法')
        that.mtuTimer = setInterval(() => {
            console.log('开始循环设置MTU值')
            wx.setBLEMTU({
                deviceId,
                mtu: 512,
                success(res) {
                    console.log('设置mtu成功')
                },
                fail(err) {
                    console.error(err)
                },
                complete() {
                    that.getBLEMTU().then((mtu) => {
                        clearInterval(that.mtuTimer)
                        that.mtuTimer = null;
                    })
                }
            })
        }, 1500)
    }
    // 设备连接
    connectBluetooth(deviceId) {
        let that = this;
        that.deviceId = deviceId;
        return new Promise((reslove, reject) => {
            wx.createBLEConnection({
                deviceId,
                async success(res) {
                    this.notifyPromise = null
                    console.log("连接成功设备---" + JSON.stringify(res));
                    // wx.showToast({ 
                    //   title: '连接成功',
                    //   icon: 'success' 
                    // })
                    let serviceId = await that.getBluetoothServers(deviceId);
                    let characteristicId = await that.getBluetoothCharacteristics(deviceId, serviceId);
                    console.log("获取服务id和特征值id", serviceId, characteristicId);
                    await that.getSystemInfo()
                    reslove({
                        deviceId,
                        serviceId,
                        characteristicId
                    })
                },
                fail(err) {
                    // wx.showModal({
                    //     title: '提示',
                    //     showCancel: false,
                    //     content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
                    // })
                    wx.showToast({ 
                      title: '连接失败',
                      icon: 'error' 
                    })
                    console.log("连接失败，结束---" + JSON.stringify(err));
                    that.closeConnectBluetooth();
                    reject()
                },
            });
        })

    }
    // 断开连接
    closeConnectBluetooth(deviceId) {
        let that = this;
        if (deviceId) {
            // 断开BLE的连接
            wx.closeBLEConnection({
                deviceId,
                success(res) {
                    console.log("手动断开连接", res);
                },
            });
        }
        // 断开蓝牙的连接 （初始化所有的状态）
        wx.closeBluetoothAdapter({
            success(res) {
                app.globalData.bleDisNetwork = {};
                console.log("断开蓝牙", res);
            },
        });
    }
    // 获取设备的服务
    getBluetoothServers(deviceId) {
        let that = this;
        return new Promise((reslove) => {
            wx.getBLEDeviceServices({
                deviceId,
                success(res) {
                    console.log("获取设备服务=====", res);
                    let serviceId = app.globalData.serviceId;
                    that.serviceId = serviceId;
                    reslove(serviceId);
                },
            });
        })

    }
    // 获取设备某个服务特征值列表
    getBluetoothCharacteristics(deviceId, serviceId) {
        let that = this;
        return new Promise((reslove) => {
            wx.getBLEDeviceCharacteristics({
                deviceId,
                serviceId,
                success(res) {
                    console.log("获取设备某个服务特征值列表", res);
                    let characteristicId = app.globalData.characteristicId;
                    that.characteristicId = characteristicId;
                    reslove(characteristicId);
                },
            });
        })

    }

    // 向设备特征值中写入二进制数据, arr 传入 buffer
    writeBluetoothCharacteristicValue(arr) {
        let that = this;
        // 下发指令 
        // console.info('获取信息 转化 Buffer', utils.strToBuf(arr))
        return new Promise((reslove, reject) => {
            wx.writeBLECharacteristicValue({
                deviceId: that.deviceId,
                serviceId: that.serviceId,
                characteristicId: that.characteristicId,
                value: arr,
                success(res) {
                    // console.log(res, "写入成功");
                    // that.readBinaryData();
                    reslove(res);
                },
                fail(res) {
                    console.log(res, "写入失败 结束");
                    reject(res);
                }
            })
        })

    }
    // 读取二进制数据
    readBinaryData() {
        let that = this;
        wx.readBLECharacteristicValue({
            deviceId: that.deviceId,
            serviceId: that.serviceId,
            characteristicId: that.characteristicId,
            success(res) {
                console.log(res, "读取成功");
            },
            fail(res) {
                console.log(res, "读取失败 结束")
            }
        })
    }
    notifyBLECharacteristicValueChange() {
        // 监听设备的特征值变化
        if (this.notifyPromise) {
            return this.notifyPromise
        }
        console.log("监听设备的特征值变化")
        this.notifyPromise = new Promise((reslove, reject) => {
            //当打印机需要向小程序返回数据时（如打印状态确认、错误信息等），数据会通过这个通道自动传输，无需小程序主动查询
            //在蓝牙打印场景中，小程序通过 wx.writeBLECharacteristicValue 向打印机发送打印指令，而 wx.notifyBLECharacteristicValueChange 则负责接收打印机返回的响应信息，形成了完整的双向通信机制
            wx.notifyBLECharacteristicValueChange({
                state: true, // 启用 notify 功能  ?notify实际示例 实施推送剩余智障?
                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                deviceId: this.deviceId,
                // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                serviceId: this.serviceId,
                // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                characteristicId: app.globalData.notifyId,
                success(res) {
                    console.log("notifyBLECharacteristicValueChange成功", res);
                    reslove()
                },
                fail(err) {
                    console.log("notifyBLECharacteristicValueChange失败", err);
                    reject()
                }
            })
        })
        return this.notifyPromise
    }
    // 读取设备的特征值
    async onBLECharacteristicValueChange(fn) {
        await this.notifyBLECharacteristicValueChange()
        fn && wx.onBLECharacteristicValueChange(fn)
    }
    // 取消监听设备的特征值变化
    offBLECharacteristicValueChange() {
        wx.offBLECharacteristicValueChange()
        this.notifyPromise = null
    }
}

export default new BleDisNetwork();